
import matplotlib.pyplot as plt
import re
import numpy as np

import setting

def C(c, x):
	rou = x/c
	A = np.math.factorial(c)/((c*rou)**c)
	B = sum((c*rou)**k/np.math.factorial(k) for k in range(c))
	return 1/(1+ (1-rou)*A*B)

def MMC(c,la,mu):
	return C(c,la/mu)/(c*mu-la)+1/mu

def parse_result(path):
	f=open(path)
	lines = f.readlines()
	f.close()
	ts = []
	for line in lines:
		mat = re.match("operation number=(.+)?",line)
		if mat:
			opnumber = int(mat.groups()[0])
			ts.append(opnumber)
	for line in lines:
		mat = re.match("average time=(.+)?",line)
		if mat:
			averagetime = float(mat.groups()[0])
			ts.append(averagetime)
	return ts


def get_data(prefix="partial-200-0.05"):
	ret =[[],[]]
	for i in np.arange(0.2,2.1,0.2):
		ts = parse_result("result//20180730//%s-%0.1f.txt"%(prefix,i))
		ret[0].append(ts[0])
		ret[1].append(ts[1])
	return ret



def opnumber(sequ,partial, save=None):
	plt.clf()
	lam = np.arange(0.2,2.1,0.2)
	r = np.int32(np.array(sequ)/200.0*300)
	plt.plot(lam,r,"r.-",label="Sequential")
	r = np.int32(np.array(partial)/200.0*300)
	plt.plot(lam,r,"b^-",label=setting.system_name)
	plt.xlabel("$\lambda$ ($s^{-1}$)")
	plt.ylabel("Operation Number")
	# if title:
	# 	plt.title(title)
	plt.grid(linestyle='--')
	plt.legend()
	if save:
		plt.savefig("figs/infoco/%sopnum.png"%save,dpi=400,bbox_inches="tight")
		plt.savefig("figs/infoco/%sopnum.eps"%save,dpi=400,bbox_inches="tight")
	plt.show()

def avg_opnumber(sequ,partial, save=None):
	plt.clf()
	lam = np.arange(0.2,2.1,0.2)
	r = np.array(sequ)/200.0
	plt.plot(lam,r,"r.-",label="Sequential")
	r = np.array(partial)/200.0
	plt.plot(lam,r,"b^-",label=setting.system_name)
	plt.xlabel("$\lambda$ ($s^{-1}$)")
	plt.ylabel("Average Operation Number")
	# if title:
	# 	plt.title(title)
	plt.grid(linestyle='--')
	plt.legend()
	if save:
		plt.savefig("figs/infoco/%savgopnum.png"%save,dpi=400,bbox_inches="tight")
		plt.savefig("figs/infoco/%savgopnum.eps"%save,dpi=400,bbox_inches="tight")
	plt.show()



def time_2line(sequ,partial, save=None, ylim=None):
	plt.clf()
	lam = np.arange(0.2,2.1,0.2)
	if ylim:
		plt.ylim(ylim)
	plt.plot(lam,sequ,"r.-",label="Sequential")
	plt.plot(lam,partial,"b^-",label=setting.system_name)
	plt.xlabel("$\lambda$ ($s^{-1}$)")
	plt.ylabel("Time (s)")
	plt.grid(linestyle='--')
	plt.legend()
	if save:
		plt.savefig("figs/infoco/%stime.png"%save,dpi=400,bbox_inches="tight")
		plt.savefig("figs/infoco/%stime.eps"%save,dpi=400,bbox_inches="tight")
	plt.show()


def time_1line(sequ, save=None, ylim=None):
	plt.clf()
	lam = np.arange(0.2,2.1,0.2)
	if ylim:
		plt.ylim(ylim)
	plt.plot(lam,sequ,"r.-",label="Sequential")
	# plt.plot(lam,partial,"b^-",label=setting.system_name)
	plt.xlabel("$\lambda$ ($s^{-1}$)")
	plt.ylabel("Average Update Time (s)")
	plt.grid(linestyle='--')
	plt.legend()
	if save:
		plt.savefig("figs/infoco/%stime.png"%save,dpi=400,bbox_inches="tight")
		plt.savefig("figs/infoco/%stime.eps"%save,dpi=400,bbox_inches="tight")
		plt.savefig("figs/infoco/%stime.pdf"%save,dpi=400,bbox_inches="tight")
	plt.show()


def time(sequ,partial):
	plt.clf()
	lam = np.arange(0.2,2.1,0.2)
	plt.plot(lam,sequ,"r.-",label="Sequential")
	plt.plot(lam,partial,"b^-",label=setting.system_name)
	mu = 1.0/sequ[0]
	lam1 = np.arange(0.2,mu,0.02)
	y = 1/(mu - lam1)
	print(y)
	plt.plot(lam1,y,"g--",label="M/M/1")
	mu = 1.0/sequ[0]
	lam1 = np.arange(0.2,2.2,0.02)
	y = [MMC(20,la,mu) for la in lam1]
	print(y)
	plt.plot(lam1,y,"r--",label="M/M/C")
	plt.xlabel("$\lambda$ ($s^{-1}$)")
	plt.ylabel("Time (s)")

	# ax = plt.gca()
	# nnn = np.linspace(0.5,2.5,5)
	# ax.set_yticks(nnn)
	# la = [str(a) for a in nnn]
	# ax.set_yticklabels(la)
	plt.grid(linestyle='--')
	plt.legend()
	plt.show()
	# fig.savefig("figs/averagetime.pdf",dpi=400,bbox_inches="tight")

def op_ratio(sequ,partial, p_list):
	lam = np.arange(0.2,2.1,0.2)
	styles = ["r.-","b^-","g.-","r"]
	labels = ["p=%.1f"%i for i in p_list]
	for i in range(4):
		r = [m/float(n) for m,n in zip(partial[p_list[i]][0],sequ[p_list[i]][0])]
		plt.plot(lam,r,styles[i],label=labels[i])
	plt.xlabel("$\lambda$ ($s^{-1}$)")
	plt.title("Operation Reduction")
	plt.legend()
	plt.show()


def p_time(partial, p_list):
	fig = plt.gcf()
	fig.set_size_inches(4,3)
	lam = np.arange(0.2,2.1,0.2)
	labels = ["p=%.1f"%i for i in p_list]
	print(partial.keys())
	for i in range(4):
		r = partial[p_list[i]][1]
		plt.plot(lam,r,color=setting.colors[p_list[i]],marker=setting.markers[p_list[i]],label=labels[i])
	plt.xlabel("$\lambda$ ($s^{-1}$)")
	# plt.title("Time")
	plt.ylabel("Time(s)")
	plt.legend()
	plt.grid(linestyle='--')
	if setting.save:
		fig.savefig("figs/infoco/completiontime.eps",dpi=400,bbox_inches="tight")
		fig.savefig("figs/infoco/completiontime.pdf",dpi=400,bbox_inches="tight")
	plt.show()

def p_time_2(sequ, partial, p_list):
	fig = plt.gcf()
	fig.set_size_inches(4,3)
	lam = np.arange(0.2,2.1,0.2)
	labels = ["p=%.1f"%i for i in p_list]
	print(partial.keys())
	for i in range(len(p_list)):
		r = sequ[p_list[i]][1]
		plt.plot(lam,r,color=setting.colors[p_list[i]],marker=setting.markers[p_list[i]],label=labels[i]+",Sequential")
		r = partial[p_list[i]][1]
		plt.plot(lam,r,color=setting.colors[p_list[i]],linestyle="--",marker=setting.markers[p_list[i]],label=labels[i]+","+setting.system_name)
	plt.xlabel("$\lambda$ ($s^{-1}$)")
	# plt.title("Time")
	plt.ylabel("Time(s)")
	plt.legend()
	plt.grid(linestyle='--')
	if setting.save:
		fig.savefig("figs/infoco/completiontime.eps",dpi=400,bbox_inches="tight")
		fig.savefig("figs/infoco/completiontime.pdf",dpi=400,bbox_inches="tight")
	plt.show()

def p_number(sequ, partial, p_list):
	fig = plt.gcf()
	width =4.0
	fig.set_size_inches(width,width/4.0*3.7)
	# plt.ylim(42,62)
	lam = np.arange(0.2,2.1,0.2)
	labels = ["p=%.1f"%i for i in p_list]
	print(partial.keys())
	for i in range(len(p_list)):
		r = partial[p_list[i]][0]
		r = np.array(r)/200.0
		plt.plot(lam,r,color=setting.colors[p_list[i]],marker=setting.markers[p_list[i]],label=labels[i]+","+setting.system_name)
		r = sequ[p_list[i]][0]
		r = np.array(r)/200.0
		plt.plot(lam,r,color=setting.colors[p_list[i]],linestyle="--",marker=setting.markers[p_list[i]],label=labels[i]+",Sequential")
	plt.xlabel("$\lambda$ ($s^{-1}$)")
	# plt.title("Time")
	plt.ylabel("Average Operation Number")
	from matplotlib.lines import Line2D

	
	l = []
	w = []
	for i in range(len(p_list)):
		# l.append(Line2D([0],[0],color=setting.colors[p_list[i]], marker=setting.markers[p_list[i]]))
		l.append(Line2D([0],[0],color='w', marker=setting.markers[p_list[i]], markerfacecolor=setting.colors[p_list[i]], markersize=8))
		w.append("p=%.1f"%p_list[i])

	l.append(Line2D([0],[0],linestyle="--",color='black'))
	w.append("Sequential")
	l.append(Line2D([0],[0],linestyle="-",color='black'))
	w.append("Update Algebra")	
	plt.legend(l,w)
	plt.grid(linestyle='--')
	# plt.legend()
	if setting.save:
		fig.savefig("figs/infoco/opnum.eps",dpi=400,bbox_inches="tight")
		fig.savefig("figs/infoco/opnum.pdf",dpi=400,bbox_inches="tight")
	plt.show()


partial = {}
sequ = {}


# for i in range(0,9):
# 	partial[i/10.0] = get_data("partial-200-%.1f"%(i/10.0))
# 	sequ[i/10.0] = get_data("sequ-200-%.1f"%(i/10.0))


partial = {0.0: [[12117, 12094, 12055, 11912, 11739, 11422, 10952, 10581, 9901, 9256], [0.91022887826, 0.986547501087, 1.08579843998, 1.24694108605, 1.40924274087, 1.63899425864, 1.87945570827, 2.10566966653, 2.45609910488, 2.7113963604]], 0.1: [[11828, 11762, 11717, 11513, 11415, 11067, 10651, 10348, 9786, 9183], [0.90388455987, 0.963937040567, 1.04419888496, 1.19438948274, 1.3142197299, 1.53528458357, 1.75028311968, 1.90906930566, 2.19300016522, 2.47531570792]], 0.3: [[11834, 11734, 11540, 11204, 11017, 10768, 10450, 10171, 9643, 9127], [0.893796497583, 0.951296243668, 1.02265138149, 1.11594220996, 1.22770605445, 1.39016872048, 1.61441234231, 1.70447517037, 2.07616527796, 2.3517556107]], 0.6: [[11829, 11638, 11224, 10903, 10626, 10274, 9842, 9635, 9276, 8932], [0.889432446957, 0.922692161798, 0.980317208767, 1.04887582183, 1.1711670959, 1.28037560105, 1.39207485318, 1.48847567081, 1.70175418139, 1.83046495795]], 0.8: [[11760, 11574, 11082, 10576, 10201, 9835, 9380, 9094, 8801, 8454], [0.874661070108, 0.907532470226, 0.931761009693, 0.991256116629, 1.06071421504, 1.1573093605, 1.18786219001, 1.27352685809, 1.39886506677, 1.45965405464]], 0.5: [[11688, 11618, 11287, 10940, 10575, 10292, 9864, 9655, 9292, 8911], [0.884668755531, 0.922026990652, 0.972402070761, 1.05345224261, 1.18386266828, 1.31466492414, 1.39200925469, 1.47547974467, 1.73550961852, 1.94495164394]], 0.7: [[11803, 11684, 11198, 10781, 10503, 10111, 9696, 9374, 9082, 8773], [0.882707664967, 0.917833180428, 0.962288742065, 1.0266404736, 1.12629184008, 1.23712426305, 1.32191113591, 1.40752242088, 1.58520683289, 1.67922127128]], 0.2: [[11567, 11491, 11366, 11203, 11007, 10719, 10445, 10178, 9684, 9092], [0.88823307991, 0.945126324892, 0.997256073952, 1.12357692242, 1.24417733908, 1.42253305435, 1.68807894945, 1.83915941715, 2.15728419423, 2.46462894917]], 0.4: [[11857, 11718, 11360, 11099, 10854, 10574, 10153, 9886, 9367, 9029], [0.883850104809, 0.94435965538, 1.0047678721, 1.11286296844, 1.22335781693, 1.34951158524, 1.50182537556, 1.64488768339, 1.89409698844, 2.19772537947]]}
sequ = {0.0: [[12117, 12117, 12117, 12117, 12117, 12117, 12117, 12117, 12117, 12117], [0.916850627661, 0.9959679842, 1.18892089367, 1.67384823918, 2.90090305805, 14.1977537644, 22.633225826, 27.5140478301, 33.3200017083, 37.5945037365]], 0.1: [[11841, 11841, 11841, 11841, 11841, 11841, 11841, 11841, 11841, 11841], [0.911292796135, 0.986752960682, 1.16190695524, 1.6557734561, 2.73922118902, 13.0427828991, 21.58978953, 26.4565160918, 32.2998250377, 36.5416443634]], 0.3: [[11973, 11973, 11973, 11973, 11973, 11973, 11973, 11973, 11973, 11973], [0.914265497923, 0.995809439421, 1.15876837969, 1.62221486688, 2.76128742695, 13.4801924312, 21.9584832156, 26.8207268882, 32.6585625112, 36.9407680285]], 0.6: [[12134, 12134, 12134, 12134, 12134, 12134, 12134, 12134, 12134, 12134], [0.930627993345, 1.00397442222, 1.1777208972, 1.6599014461, 2.99276324272, 14.4958035111, 22.8798176682, 27.7518332231, 33.5957967508, 37.8357373118]], 0.8: [[12155, 12155, 12155, 12155, 12155, 12155, 12155, 12155, 12155, 12155], [0.929954373837, 1.00571544886, 1.18096161008, 1.71620176315, 3.08997521043, 14.7468396342, 23.1959674132, 28.0128676903, 33.8999119163, 38.0792626321]], 0.5: [[11965, 11965, 11965, 11965, 11965, 11965, 11965, 11965, 11965, 11965], [0.916803572178, 0.9872179842, 1.14518956423, 1.6114482975, 2.92456161976, 13.8334320486, 22.1749171436, 27.0465209699, 32.8645061266, 37.1863782001]], 0.7: [[12172, 12172, 12172, 12172, 12172, 12172, 12172, 12172, 12172, 12172], [0.928776159286, 0.999671156406, 1.17567991257, 1.68805835962, 2.94663674712, 14.3865735984, 22.7843881238, 27.6404583216, 33.4832378006, 37.7393819511]], 0.2: [[11640, 11640, 11640, 11640, 11640, 11640, 11640, 11640, 11640, 11640], [0.907271900177, 0.984713692665, 1.13213496327, 1.56103817225, 2.56502423763, 12.715599798, 21.1848109591, 26.0670793664, 31.9055451393, 36.1482026005]], 0.4: [[12071, 12071, 12071, 12071, 12071, 12071, 12071, 12071, 12071, 12071], [0.917944079638, 1.00095938206, 1.17713733315, 1.63153140187, 2.85519830823, 14.1597655582, 22.6793545806, 27.4899992907, 33.3547778189, 37.863425132]]}

print(partial)
print(sequ)

import matplotlib
matplotlib.rcParams['xtick.direction']='in'
matplotlib.rcParams['ytick.direction']='in'


r=0.6
matplotlib.rcParams["figure.figsize"]=[6.4*r,4.8*r]

print(matplotlib.rcParams)

# opnumber(sequ[0.2][0],partial[0.2][0], "p=0.2")
# avg_opnumber(sequ[0.2][0],partial[0.2][0], "p=0.2")
# time_2line(sequ[0.2][1],partial[0.2][1], "p=0.2")
time_1line(sequ[0.2][1], "p=0.2")
# time_2line(sequ[0.2][1],partial[0.2][1], save="p=0.2trim", ylim=(0.5,3.0))
# op_ratio(sequ,partial,[0.05,0.2,0.4,0.6])
# p_time(partial, [0.0,0.2,0.4,0.8])
# p_number(sequ, partial, [0.0,0.2,0.4,0.8])
# p_time_2(sequ, partial, [0.2,0.3,0.4,0.5,0.7,0.8])



a=partial[0.2][1][7]
b=sequ[0.2][1][7]

print(a,b)
sa = 1.0/a
sb =1.0/b

print((sa-sb)/sb)



a=partial[0.8][0][9]
b=sequ[0.8][0][9]

print(a,b)
print((a-b)/b)
